package org.agile4j.plugin.soap;

import java.util.ArrayList;
import java.util.List;

import org.apache.cxf.frontend.ClientProxyFactoryBean;
import org.apache.cxf.frontend.ServerFactoryBean;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.message.Message;

/**
 * SOAP 助手类
 * 
 * @author hanyx
 * @since 1.0.0
 */
public class SoapHelper {
	private static final List<Interceptor<? extends Message>> inInterCeptorList = new ArrayList<>();
	private static final List<Interceptor<? extends Message>> outInterCeptorList = new ArrayList<>();

	// 初始化 日志拦截器
	static {
		// 添加 Logging Interceptor
		if (SoapConfig.isLog()) {
			LoggingInInterceptor loggingInInterceptor = new LoggingInInterceptor();
			inInterCeptorList.add(loggingInInterceptor);
			LoggingOutInterceptor loggingOutInterceptor = new LoggingOutInterceptor();
			outInterCeptorList.add(loggingOutInterceptor);
		}
	}
	
	/**
	 * 发布 SOAP 服务
	 */
	public static void publishService(String wsdl, Class<?> interfaceClass, Object implementInstance) {
		ServerFactoryBean factory = new ServerFactoryBean() ;
		factory.setAddress(wsdl);
		factory.setServiceClass(interfaceClass);
		factory.setServiceBean(implementInstance);
		factory.setInInterceptors(inInterCeptorList);
		factory.setOutInterceptors(outInterCeptorList);
		factory.create();
	}
	
	/**
	 * 创建 SOAP 客户端
	 */
	public static <T> T createClient(String wsdl, Class<? extends T> interfaceClass) {
		ClientProxyFactoryBean factory = new ClientProxyFactoryBean() ;
		factory.setAddress(wsdl);
		factory.setServiceClass(interfaceClass);
		factory.setInInterceptors(inInterCeptorList);
		factory.setOutInterceptors(outInterCeptorList);
		return factory.create(interfaceClass) ;
	}
}
